package cn.jsu.oj.judgment.net;

import cn.jsu.oj.judgment.config.ResourceConfig;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component("judgeWriteClient")
public class JudgeWriteClient {

    private Bootstrap bootstrap;

    public static ChannelFuture channelFuture;

    private static final String IP = ResourceConfig.getConfigString("net.server.write.ip");

    private static final Integer PORT = ResourceConfig.getConfigInteger("net.server.write.port");

    public void init() {
        this.bootstrap = new Bootstrap();
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        JudgeChannelInit writeChannelInit = new JudgeChannelInit("judgeWriteClientHandler");
        Objects.requireNonNull(this.bootstrap, "----------引导器配置失败......")
                .group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(writeChannelInit);
        log.info("----------判题机通道处理节点配置完成......");
    }


    public void start() {
        channelFuture = this.bootstrap.connect(IP, PORT);
        if (!channelFuture.isSuccess()) {
            channelFuture.channel().closeFuture();
            return;
        }
        try {
            channelFuture.sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
